<template>
  <div class="user-layout absolute inset-0 flex flex-col">
    <Pageheader
      pageheaderName="User Management"
      style="margin-bottom: 9px"
      :isMode="false"
    />

    <ZContainer v-loading="resourceLoading" class="user-grid">
      <BUserActions
        actionCls="user-grid-actions flex"
        @addUser="() => onOpenUserModal('add')"
        @setPermission="setPermission"
        :disablednonCwUserbtn="disablednonCwUserbtn"
        :disablednonAutoTaskbtn="disablednonAutoTaskbtn"
        :dashboardUserCount="dashboardUserCount"
        :billableUserCount="billableUserCount"
        @search="onSearch"
        @batchDisabled="batchDisableUserBefore"
      />

      <BGrid
        :columns="columns"
        :dataSource="resources"
        :allowExcelExport="true"
        :allowFiltering="true"
        :showColumnChooser="true"
        :allowGrouping="false"
        :allowPdfExport="true"
        :allowReordering="true"
        :allowResizing="true"
        :allowSorting="true"
        :allowTextWrap="true"
        :filterSettings="{
          type: 'Excel'
        }"
        :toolbar="[
          // 'ExcelExport',
          'PdfExport',
          'CsvExport',
          'Search',
          'ColumnChooser'
        ]"
        :sortSettings="{
          columns: [{ field: 'roles', direction: 'Ascending' }]
        }"
        class="user-grid-e h-0"
        :selectionSettings="{
          type: 'Multiple'
        }"
        :rowSelected="rowSelected"
        :load="load"
        ref="b-grid"
      />
    </ZContainer>

    <el-dialog
      :visible.sync="userModalVisible"
      :title="userModalTitle"
      destroy-on-close
      append-to-body
      custom-class="user-modal"
      width="920px"
    >
      <UserEditForm v-if="userModalType === 'edit'" :detail="selectRow" />
      <UserAddForm v-if="userModalType === 'add'" :settings="settings" />
    </el-dialog>

    <UserSetRoleModal :visible.sync="roleModalVisible" />
  </div>
</template>

<script>
import Pageheader from '@/components/viewComponents/pageheader'
import ZContainer from '@/components/storybook/z-container'
import BGrid from '@/components/storybook/b-grid'
import BUserActions from '@/components/storybook/b-user-actions/index'
import {
  fetchUserList,
  fetchQueryNumber,
  fetchWorkScheduledUser,
  fetchConnect,
  deleteUser
} from '@/api/new'
import { renderColumns } from './index.schema'
import { merge } from 'lodash'
import { PAGE_SETTING } from '@/components/storybook/settings/page'
import UserAddForm from './components/user-add-form.vue'
import UserEditForm from './components/user-edit-form.vue'
import CONFIG from '@/utils/config'
import UserSetRoleModal from './components/user-set-role-modal'
import bus from '@/components/storybook/utilties/bus'

export default {
  name: 'User',
  components: {
    Pageheader,
    ZContainer,
    BGrid,
    BUserActions,
    UserAddForm,
    UserEditForm,
    UserSetRoleModal
  },
  data () {
    return {
      resourceLoading: false,
      userModalType: undefined,
      roleModalVisible: false,
      resources: [],
      selectRow: {},
      connect: [],
      settings: {},
      users: [],
      searchForm: {
        status: 1,
        pagination: merge(PAGE_SETTING, {
          total: 0
        })
      }
    }
  },
  computed: {
    columns () {
      return renderColumns(this.settings)
    },
    userModalVisible: {
      get () {
        return !!this.userModalType
      },
      set (val) {
        this.userModalType = val || undefined
      }
    },
    userModalTitle () {
      return this.userModalType === 'add' ? this.$t('add') : this.$t('update')
    },
    dashboardUserCount () {
      return this.users.filter(i => i.roleList.includes('Dashboard Only'))
        .length
    },
    billableUserCount () {
      const isInRole = roles =>
        roles.some(i => i.id === CONFIG.roleDashboardOnlyId)
      return this.resources.filter(
        i => !isInRole(i.roleList || []) && i.status === 1
      ).length
    },
    disablednonCwUserbtn () {
      return this.connect.some(i => i.configCode === 'CW' && i.status === 1)
    },
    disablednonAutoTaskbtn () {
      return this.connect.some(
        i => i.configCode === 'AUTOTASK' && i.status === 1
      )
    }
  },
  created () {
    this.init()
  },
  activated () {
    this.activatedEvent()
  },
  deactivated () {
    this.destroyedEvent()
  },

  beforeDestroy () {
    this.destroyedEvent()
  },
  methods: {
    activatedEvent () {
      bus.$on('event:edit', data => {
        this.selectRow = data
        this.onOpenUserModal('edit')
      })
    },
    destroyedEvent () {
      bus.$off('event:edit')
    },
    rowSelected () {
      if (this.$refs['b-grid']) {
      }
    },
    load () {},
    async init () {
      try {
        this.resourceLoading = true
        const [resources, users, connect] = await Promise.all([
          this.getTableData(),
          this.getUsers(),
          this.getConnect()
        ])
        const arr = (resources.records || []).map(({ roleList, ...rest }) => {
          return {
            ...rest,
            roleList,
            roles: (roleList || []).map(({ name }) => name).join()
          }
        })
        this.resources = arr
        this.connect = connect
        this.settings = resources.setting
        this.users = users
      } catch (error) {
      } finally {
        this.resourceLoading = false
      }
    },
    setPermission () {
      const selectedRows =
        this.$refs['b-grid'].getInstance().getSelectedRecords() || []
      if (!selectedRows.length) {
        return this.$message.warning('Please selected user')
      }
      const isSelf = selectedRows.some(i => i.id === this.$store.state.user.id)

      if (isSelf) {
        return this.$message.warning(`You can't set your own role`)
      }

      this.roleModalVisible = true
    },
    async getConnect () {
      try {
        const params = {
          tenantCode: this.$store.state.user.tenantCode
        }
        const { data: response } = await fetchConnect(params)
        if (response.code !== 0) {
          throw response.msg
        }
        return response.data || []
      } catch (error) {
        console.log(error)
        return []
      }
    },
    async onSearch (status) {
      this.resourceLoading = true
      this.searchForm.status = status
      await this.getTableData()
      this.resourceLoading = false
    },
    async getUsers () {
      try {
        const { data: response } = await fetchWorkScheduledUser({
          tenantCode: this.$store.state.user.tenantCode,
          regSource: '1'
        })
        return response.data || []
      } catch (error) {
        console.log(error)
        return []
      }
    },
    async getQueryNumber () {
      try {
        await fetchQueryNumber()
      } catch (error) {
        console.log(error)
      }
    },

    batchDisableUserBefore () {
      try {
        const selectedRows =
          this.$refs['b-grid'].getInstance().getSelectedRecords() || []

        if (!selectedRows.length) {
          return this.$message.error(this.$t('custom.tips.selectItem'))
        }

        const selfUser = selectedRows.find(
          i => i.id === this.$store.state.user.id
        )

        if (selfUser) {
          return this.$message.error(this.$t('custom.tips.disabledSelf'))
        }

        this.disableModalVisible = selectedRows.some(
          item =>
            !item.isGuestUser && (item.cwUserName || item.autoTaskUserName)
        )

        if (!this.disableModalVisible) {
        }
      } catch (error) {
        console.log(error)
      }
    },
    async batchDisableUsers () {
      try {
        await this.$confirm(
          this.$t('prompt.info', {
            handle: this.$t('custom.sys.user.disabledBatch')
          }),
          this.$t('prompt.title'),
          {
            confirmButtonText: this.$t('confirm'),
            cancelButtonText: this.$t('cancel'),
            type: 'warning'
          }
        )

        await deleteUser()
      } catch (error) {}
    },
    batchEnableUser () {},
    batchDeleteUser () {},
    getUserByStatus () {},
    async getTableData (refresh) {
      try {
        const { pagination, ...restSearch } = this.searchForm

        const params = {
          current: 1,
          size: 999999,
          ...restSearch,
          queryType:
            refresh || this.$store.state.REFRESHCACHE ? 'REFRESHCACHE' : null
        }
        const { data: response } = await fetchUserList(params)

        if (response.code !== 0) {
          throw response.msg
        }

        return response.data || {}
      } catch (error) {
        console.log(error)
        return {}
      }
    },
    onOpenUserModal (type) {
      this.userModalType = type
    },
    onSuccess () {},
    onClosed () {},
    syncTeamsUser () {},
    autoMapUser () {},
    changeStatus () {},
    changeSwitchMessage () {},
    changePassword () {},
    onDelete () {},
    addHomeChannel () {},
    setManager () {}
  }
}
</script>

<style lang="scss" scoped>
.user-grid {
  &-actions {
    border-bottom: 1px solid #dde1e6;
    padding-bottom: 16px;
  }
  &-e {
    margin-top: 16px;
  }
}
</style>
